#!/usr/bin/perl -w
use strict;
use constant DEBUG => 1;
#use Mail;
#use Socket;
use DBI;
use dba;
#use parse;
use sock;

#my $log_get=$dba::h->prepare("INSERT DELAYED McLog (`client`,`req`,`uri`,`ask`) values (?,?,?,?)");
#$log_get->execute($ENV{'REMOTE_ADDR'},$ENV{'REQUEST_METHOD'},$ENV{'REQUEST_URI'},undef) or warn $DBI::errstr;

#print "Content: text/one\nDate: Fri, 30 Jan 2004 09:59:31 GMT\n\n";

undef local $/;
$_=<STDIN>; # Must Be After Write into STDOUT!!!!

sub ans($);
sub DefAns(;@);
# pass 1
#print "Readed: ",$_||"''";
#print "\n";
#print("Error in request: $_"),
warn("Error request"),print DefAns('ErrorRequest') unless $_ && m{<mcafeeupdater(.*?)>(.*)</mcafeeupdater>}s;
#print "Found: $1, $2\n";
my $ask=$2;
$_=$1;
my @all=m{(\w+)=\"([^\"]*)\"}g;
push @all,($ask =~ m{<([^<>]+?)>(.*?)</.*?>}sg);
my %ask=@all;

$_=$ENV{'REMOTE_ADDR'};
$_=$ENV{'HTTP_X_FORWARDED_FOR'}
if /^((?:198\.22|192\.168)\.1[67].1[678]|127\.0\.0)\.\1$/ && exists $ENV{'HTTP_X_FORWARDED_FOR'};

$ask{'REMOTE_ADDR'}=$_;

#printf "Found %d variables\n",scalar keys %ask;print "$_ = $ask{$_}\n" foreach sort keys %ask;

if (exists($ask{'email'}))
{
my @known=qw/customerid firstname lastname address1 address2 city state zip country phone email machineid specialoffers receiveannounc purchasemethod/;
my @p0=map $ask{$_},@known;
my $pv=join ',',map"`$_`",@known;
my $pq=join ',',map'?',@known;
my $log_ask=$dba::h->prepare(qq/INSERT `McReg` ($pv) values ($pq)/);
$log_ask->execute(@p0) or warn $DBI::errstr;
$log_ask->finish();

ans($ask{'customerid'});
} else {

my ($ver)=
#4976;
$dba::h->selectrow_array(qq/select ver from McUpd order by id desc limit 1/);

$ver++;

my @known=map "`$_`",qw/McAfee McAsk client iver ilang iid prod oem ver lang os/;
my @known2=qw/REMOTE_ADDR version language customerid productid oemid productversion productlanguage productos/;
my @p0=map $ask{$_},@known2;
my $table=shift @known;
my $tablea=shift @known;
my $pv=join ',',@known;
my $pq=join ',',map '?',@known;

my $log_ask=$dba::h->prepare(qq/INSERT $tablea ($pv) values ($pq)/);
$log_ask->execute(@p0) or warn $DBI::errstr;
$log_ask->finish();

$_=$dba::h->quote($ask{'productid'});

($_)=$dba::h->selectrow_array(qq/SELECT `res` FROM $table WHERE `id`=$_ ORDER BY `version` DESC LIMIT 1/);
unless ($_)
{
    unless(defined$_)
    {
    @known=map "`$_`",qw/id language oemid os version res/;
    @known2=qw/productid productlanguage oemid productos productversion/;
    $pv=join ',',@known;
    $pq=join ',',map '?',@known;
    @p0=map $ask{$_},@known2;
    my $a=$dba::h->prepare(qq/insert $table ($pv) values ($pq)/);
    $a->execute(@p0,'')||warn $DBI::errstr;
    $a->finish();
    warn 'NotFound';
    }
    $_=DefAns('NotFound');
} else {
    s{(HTTP/.*?|Proxy-Connection: .*?)\r?\n}{}sg;
    s{(<componentid>Delta</componentid>\s*<updateversion>4\.00\.)\d+(</updateversion>\s*<updatemethod>DATINCREMENTAL</updatemethod>\s*<updateurl>)[^<>]*\.ini(</updateurl>)}{$1$ver$2http://cdit/cgi-bin/McAfee/Delta.ini<ver num="$ver"/>$3}s;#?$ver
    s{http://download\.mcafee\.com/[\w\.\/]*/delta(\d+)\.ini}{http://cdit/cgi-bin/McAfee/Delta.ini}g;
    s{http://download\.mcafee\.com/[\w\.\/]*/([\w\.]*)}{http://cdit/ftp/McAfee/$1}g;
    s{<updateversion>4.3.2.0</updateversion>}{<updateversion>5.2.0.0</updateversion>}g;
    s{<updateurl>\S+/4320Eng.exe</updateurl>}{<updateurl>http://cdit/ftp/McAfee/5200Eng.exe</updateurl>}g;
}
}
print;

sub DefAns(;@)
{
    $_="Content-Type: text/xml\r\n\r\n<mcafeeupdaterresponse resultcode=\"0\" @_></mcafeeupdaterresponse>\r\n";
}
sub ans($)
{
    my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime;
    my $now=sprintf "%02u/%02u/%04u %u:%02u",$mon+1,$mday,$year+1900,$hour,$min;#04/05/2004 5:33
    $_="Content-Type: text/xml\r\n\r\n". #HTTP/1.1 200 OK\r\n
	    '<mcafeeupdaterresponse resultcode="0">'.
	    "<customerid>$_[0]</customerid>".
	    "<registrationtime>$now</registrationtime></mcafeeupdaterresponse>";
}
			
__END__

#$log_ask->execute($1,$2,$3,$4,$5,$6,$7,$8)
#if $all=~m%^<mcafeeupdater version="([^\"]+)" language="([^\"]+)" customerid="([^\"]+)" ><productid>([^<]+)</productid><oemid>(^<]+)</oemid><productversion>2.51.1003.1</productversion><productlanguage>([^<]+)</productlanguage><productos>([^<]+)</
#		    productos></mcafeeupdater>%;

#<mcafeeupdater version="2.3" language="eng" customerid="0239928" >
#<productid>CTL</productid><oemid>0</oemid><productversion>2.51.1003.1</productversion><productlanguage>ENG</productlanguage><
#productos>W9NT2K</productos></mcafeeupdater>
#


#	my %ask=parse::req($req);
	if (exists $ask{ANSWER})
	{ # we now answer!!
	    send MSOCK,$ask{ANSWER},0;
	    $db::h->do($ask{INSERT}) or die $DBI::errstr;
	} else {
#	print $req;
#	print parse::rebuild($ask{KEYS}) if DEBUG;exit;
	my ($ask,$ts)=$db::h->selectrow_array($ask{SELECT});

	print $$,' Modified: ',$ts if DEBUG;
	print $$,' Answer  :',$\,$ask if DEBUG;
			
	if ($ask && $ts<120000) # 0 day 12 hours 00 minutes 00 seconds
	{
	    send MSOCK,$ask,0;
	} else {
	wconnect($$.' Connecting to McAfee'),$con=1 unless $con;

	send SOCKET,$ask{REQ},0;
	
	my $upd=$db::h->prepare($ask{$ask?'UPDATE':'INSERT'}) or die $DBI::errstr;
	$ask='';
	my $res;
	
	while(defined recv(SOCKET,$res,10240,0) and length($res))
	{
	    next if $res =~ /^HTTP\/1\.1 100 Continue/;# whats the hell
	    $ask.=$res;
	}

	$con=0,close(SOCKET) if 1 || /Connection: close/;
	$upd->execute($ask);
	$upd->finish();
	
	print $$,' NewAnswer: ',$\,$ask if DEBUG;		
	send MSOCK,$ask,0;
	
	}
	}

<mcafeeupdater version="2.3" language="eng" customerid="0239928" >
<productid>CTL</productid><oemid>0</oemid><productversion>2.51.1003.1</productversion><productlanguage>ENG</productlanguage><
productos>W9NT2K</productos></mcafeeupdater>
